<?php
declare(strict_types=1);

namespace App\Common\Modular\Data\Serve;

use App\Common\Modular\Data\Model\ResourceChunkModel;
use Core\Basics\BasicsServe;
use Core\Service\Uploader;
use League\Flysystem\FilesystemException;

class ResourceChunkServe extends BasicsServe
{
    /**
     * @return ResourceChunkModel::class
     */
    public static function model(): string
    {
        return ResourceChunkModel::class;
    }


    /**
     * 删除大文件上传碎片
     * @param int $limit
     * @return int
     * @throws FilesystemException
     */
    public function clearFileFragment(int $limit = 50): int
    {
        $success = 0;
        $list = $this->search("`time`<?", [time() - 7200])->orderByRaw('id ASC')->limit($limit)->get();
        if (count($list) === 0) {
            return $success;
        }
        $uploader = container(Uploader::class);
        /**
         * @var ResourceChunkModel $item
         */
        foreach ($list as $item) {
            $uploader->drive('local')->delete($item->path);
            $item->delete();
            $success++;
        }
        return $success;
    }
}